from machine import Pin, SPI, PWM, WDT, RTC
import socket
import time
import network
import re
import ntptime

wdt = WDT(timeout=30000)
# 全局变量，标记led灯
p2 = PWM(Pin(12))
p2.freq(50)
p1 = PWM(Pin(33))
p1.freq(50)
led = Pin(2, Pin.OUT)

def do_connect():
      # 停
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
#         wlan.connect('303', '303303303')
        wlan.connect('iPhone', '11111111')
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
#     return wlan.ifconfig()[0]

def door():
    p2.duty_u16(8000)
    time.sleep(0.5)
    p2.duty_u16(1700)
    time.sleep(3)
    p2.duty_u16(8000)
    time.sleep(0.5)


def handle_request(client_socket):
    """
    处理浏览器发送过来的数据
    然后回送相对应的数据（html、css、js、img。。。）
    :return:
    """
    
    print("wzy1")
    # 1. 接收
    recv_content = client_socket.recv(1024).decode("utf-8")
    lines = recv_content.splitlines()  # 将接收到的http的request请求数据按照行进行切割到一个列表中
    # 2. 处理请求
    # 提取出浏览器发送过来的request中的路径
    # GET / HTTP/1.1
    # GET /index.html HTTP/1.1
    # .......
    # lines[0]

    # 提取出/index.html 或者 /
    request_file_path = re.match(r"[^/]+(/[^ ]*)", lines[0]).group(1)

    print("----提出来的请求路径是：----")
    print(request_file_path)
    
    print("test---1---")

    # 完善对方访问主页的情况，如果只有/那么就认为浏览器要访问的是主页
    if request_file_path == "/" or "/opendoor":
        request_file_path = "/home.html"
        door()
 
    try:
        # 取出对应的文件的数据内容
        with open(request_file_path, "rb") as f:
            content = f.read()
    except Exception as ret:
        # 如果要是有异常，那么就认为：找不到那个对应的文件，此时就应该对浏览器404
        print(ret)
        door()
        response_headers = "HTTP/1.1 404 Not Found\r\n"
        response_headers += "Connection: close\r\n"
        response_headers += "Content-Type:text/html;charset=utf-8\r\n"
        response_headers += "\r\n"
        response_boy = "----推门就完事-------"
        response = response_headers + response_boy
        # 3.2 给浏览器回送对应的数据
        client_socket.send(response.encode("utf-8"))
        print("test---5---")
    else:
        # 如果要是没有异常，那么就认为：找到了指定的文件，将其数据回送给浏览器即可
        response_headers = "HTTP/1.1 200 OK\r\n"
        response_headers += "Connection: close\r\n"
        response_headers += "Content-Type:text/html;charset=utf-8\r\n"
        response_headers += "\r\n"
        response_boy = content
        response = response_headers.encode("utf-8") + response_boy
        # 3.2 给浏览器回送对应的数据
        client_socket.send(response)
        print("test---6---")

    # 4. 关闭套接字
    client_socket.close()
    print("test---7---")


def tcp_server_control_led():
    print("---1---")
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 为了保证在tcp先断开的情况下，下一次依然能够使用指定的端口，需要设置
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print("---2---")
    # 2. 绑定本地信息
    tcp_server_socket.bind(("", 80))
    print("---3---")
    # 3. 变成监听套接字
    tcp_server_socket.listen(128)

    print("---4---")
    
    while True:

#         Clock.show_time()
        # 4. 等待客户端的链接
        client_socket, client_info = tcp_server_socket.accept()
        print("---5---")
        print(client_info)  # 打印 当前是哪个客户端进行了请求
        print("---6---")        
        # 5. 为客户端服务
        try:            
            handle_request(client_socket)
            try:
                print('time ing')
                ntptime.settime()
                print('time ok')
                break;
            except:
                print('time no')
                time.sleep(1)
            mytime=time.localtime()
            hour = mytime[3]+8
            minute = mytime[4]
            print("minute:",minute)
            print("hour:",hour)
            if hour == 8 and minute >= 34:
                for i in range (10):
                    led.value(1)
                    time.sleep(0.5)
                    led.value(0)
                    time.sleep(0.5)
                time.sleep(30) 
        except Exception as ret:
#             door()
            print("error:", ret)            
    print("---7---")
    # 6. 关闭套接字    
    tcp_server_socket.close()
   


def main():
    do_connect()
    # 3. 创建tcp服务器，等待客户端链接，然后根据客户端的命令控制LED灯
    tcp_server_control_led()
    wdt.feed()
    
if __name__ == "__main__":
    main()



